""" 
Copyright 2009 Texas A&M University
 
Licensed under the Apache License, Version 2.0 (the "License"); you may not use 
this file except in compliance with the License. You may obtain a copy of the 
License at

http://www.apache.org/licenses/LICENSE-2.0
  
Unless required by applicable law or agreed to in writing, software distributed 
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 
CONDITIONS OF ANY KIND, either express or implied. See the License for the 
specific language governing permissions and limitations under the License.
"""
from time import mktime
from logging import getLogger

from twisted.web.resource import Resource, NoResource
from twisted.web.server import NOT_DONE_YET

from meercat.mapreduce.inline import mapreduce
from meercat.storage.interfaces import IStorage



log = getLogger('meercat.server.rest.resource')

class MeercatResourcesResource(Resource):
    def __init__(self, storage, format='web'):
        Resource.__init__(self)
        self.storage = storage
        self.format = format
    
    def getChild(self, path, request):
        log.info('%s.getChild(path=%s, request=%s)' % (str(self),
                                                       str(path),
                                                       str(request),))
        
        try:
            if (path.strip()):
                resources = self.storage.getResources(identifier=path)
                if len(resources) == 1:
                    return MeercatResourceResource(resources[0],self.format)
        except Exception, e:
            log.error('Error loading a resource :%s' % (str(e),))
        
        return NoResource('%s is not a valid resource identifier' % (str(path),))

class MeercatResourceResource(Resource):
    isLeaf = True
    
    def __init__(self, resource, format='web'):
        Resource.__init__(self)
        self.resource = resource
        self.format = format
        self.lastModified = self.resource.getLastModified()
        try:
            self.lastModified = mktime(self.lastModified.utctimetuple())
        except Exception, e:
            log.error('Unable to parse the last modified time')
    
    def render_HEAD(self, request):
        request.setLastModified(self.lastModified)
    
    def render_GET(self, request):
        if (request.setLastModified(self.lastModified)):
            return ""
        
        request.setHeader('Content-type','text/xml')
        
        mapped = mapreduce(self.resource.getMetadata(),
                           self.format)
        if mapped:
            return str(mapped.getValue())
        
        log.error('Error encountered')
        raise Exception('Unable to get valid information')
        
        